package erp

import (
	"context"
	"encoding/json"
	"ez/apps/erp/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Emp struct {
	mgo.BaseDoc  `bson:"-" json:"-"`
	Id           int64       `json:"id" bson:"id,omitempty"`
	Name         string      `json:"name" bson:"name"`                 //名称
	Code         string      `json:"code" bson:"code"`                 //工号
	Department   *Department `json:"department" bson:"department"`     //部门
	DepartmentId int64       `json:"departmentId" bson:"departmentId"` //部门
	Phone        string      `json:"phone" bson:"phone"`               //手机
	Mail         string      `json:"mail" bson:"mail"`                 //邮箱
	Wechat       string      `json:"wechat" bson:"wechat"`             //微信
	Qq           string      `json:"qq" bson:"qq"`                     //QQ
	CreateAt     time.Time   `json:"createAt" bson:"createAt"`
	UpdateAt     time.Time   `json:"updateAt" bson:"updateAt"`
	DeleteAt     *time.Time  `json:"deleteAt" bson:"deleteAt"`
}

func (this *Emp) DocName() string { return "Emp" }
func (this *Emp) GetId() int64    { return this.Id }
func (this *Emp) SetId(id int64)  { this.Id = id }
func (this *Emp) Create() error {
	return this.GetFactory().Create(this)
}
func (this *Emp) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *Emp) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Emp) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *Emp) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Emp) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *Emp) ToString() string {
	return string(this.ToBytes())
}
func (this *Emp) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Emp) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Emp) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *Emp) LoadDepartment() {
	if this.DepartmentId == 0 {
		return
	}
	this.Department, _ = NewDepartmentCrud().FindId(this.DepartmentId)
}
func (this *Emp) ClearRelationsBeforeSave() mgo.Doc {
	this.Department = nil
	return this
}
func neverUsed_Emp() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type EmpAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Emp
	Session *ez.Session
}

func NewEmpAccessControl(model *Emp, action string, session *ez.Session) *EmpAccessControl {
	ctrl := &EmpAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.EmpAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
